package com.kancy.swing.config;

import com.kancy.swing.lang.StringUtils;
import com.kancy.swing.log.Log;

import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Config
 *
 * @author kancy
 * @date 2020/2/16 6:09
 */
public class Config {

    /**
     * 系统属性
     */
    private static Properties systemProperties = new Properties();
    /**
     * 应用属性
     */
    private static ConfigProperties appProperties;

    static {
        initConfig();
    }

    private Config() {
    }

    /**
     * 获取ConfigProperties
     * @return
     */
    public static ConfigProperties get(){
        return appProperties;
    }

    /**
     * 重新加载ConfigProperties
     * @return
     */
    public static void reload(){
        appProperties.loadProperties();
    }

    /**
     * 保存ConfigProperties
     * @return
     */
    public static void save(){
         appProperties.storeProperties();
    }

    /**
     * 获取app name
     * @return
     */
    public static String getAppName(){
        return systemProperties.getProperty("app.name","app");
    }

    /**
     * 获取SystemProperties
     * @return
     */
    public static Properties getSystemProperties(){
        return systemProperties;
    }

    /**
     * 初始化
     */
    private static void initConfig() {
        try {
            systemProperties.putAll(System.getenv());
            systemProperties.putAll(System.getProperties());
            systemProperties.load(Config.class.getClassLoader().getResourceAsStream("META-INF/app.properties"));
            String configPath = systemProperties.getProperty("app.config.path");
            if (StringUtils.isBlank(configPath)){
                String userHome = systemProperties.getProperty("user.home");
                String configFileName = systemProperties.getProperty("app.name", "app");
                configPath = String.format("%s/%s.ini", userHome, configFileName)
                        .replaceAll("\\+","/")
                        .replaceAll("/+","/");
            }
            appProperties = new ConfigProperties(configPath);

            // 添加扫描器
            addConfigRefreshListener();
        } catch (IOException e) {
            Log.error(e.getMessage(), e);
        }
    }

    /**
     * 定时刷新
     */
    private static void addConfigRefreshListener() {
        String enabled = systemProperties.getProperty("app.config.refresh.enabled", "true");
        if (Boolean.parseBoolean(enabled)){
            final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
            Runtime.getRuntime().addShutdownHook(new Thread(){
                @Override
                public void run() {
                    scheduledExecutorService.shutdown();
                    Log.info("scheduledExecutorService shutdown success.");
                }
            });
            String period = systemProperties.getProperty("app.config.refresh.period", "5000");
            scheduledExecutorService.scheduleAtFixedRate(() -> Config.reload(), 3000,
                    Integer.parseInt(period), TimeUnit.MILLISECONDS);
        }
    }

}
